package br.ufrgs.meetapp.webservices;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Element;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;
import br.ufrgs.meetapp.enums.Role;
import br.ufrgs.meetapp.enums.WebServiceResult;
import br.ufrgs.meetapp.models.Buddy;
import br.ufrgs.meetapp.models.User;
import br.ufrgs.meetapp.utils.MFTParser;


/***
 * Client used to call web services
 * @author Benites
 *
 */
public class MFTWebServiceClient {
	
	private static final String NAMESPACE = "http://fleet.mecomo.com";
//	private static final String URL = "http://10.1.1.38/ntm/fleet/mft_ws/mftWS.asmx";// test
	private static final String URL = "http://mft.mecomo.com.br/WebService_staging/mftws.asmx";//production
	
	public MFTWebServiceClient() {
		
	}
	
	// TODO: create classes that will extend WebService and they will have methods according to their names, for example 'LoginWebService'.
	// This classes will access WebService to use common methods
	
	
	/***
	 * Returns the web service result from trying to retrive a new Password by an Email sent.
	 * @param userEmail
	 * @return
	 */
	public WebServiceResult sendPasswordRetrival(String userEmail) throws IOException,
			XmlPullParserException, ParserConfigurationException {
		
		WebServiceResult passwordRetrivalResult =  WebServiceResult.UNKNOWN_ERROR;
		
		try {
			
			// Set up request
			String methodName = "AccountSendPasswordRetrival";//AccountSendPasswordRetrival
			
			SoapObject request = new SoapObject(NAMESPACE, methodName);
			
			// Add password property
			createRequestPropertyInfo(request, "userEmail", userEmail);
			
			// Get the result of the web service request
			SoapObject response = getRequestResponse(request, methodName);
			
			String sendPasswordRetrival = response.getProperty("AccountSendPasswordRetrivalResult").toString();
			
			Element documentElement = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(sendPasswordRetrival.getBytes())).getDocumentElement();
			
			passwordRetrivalResult = MFTParser.processWebServiceResult(documentElement);
			
		} catch (Exception e) {
			System.out.println("Error in MFTWebService.sendPasswordRetrival - trying to call Account_SendPasswordRetrival service");
			
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			
			e.printStackTrace();
		}
		
		return passwordRetrivalResult;
	}
	
	
	
	/***
	 * Try to log the specified user calling a web service. If web service result is not LOGIN_INPUT_ERROR, update user data. Return the web service result.
	 * @param user
	 * @param device
	 * @return
	 */
	public WebServiceResult login(User user) {
		
		WebServiceResult loginResult =  WebServiceResult.UNKNOWN_ERROR;
		
		try {
			
			// Set up request
			String methodName = "ProcessUserDevice";
			String md5Password = getMD5Password(user.getPassword());
			
			SoapObject request = new SoapObject(NAMESPACE, methodName);
			
			// Add company name property
			createRequestPropertyInfo(request, "company", user.getCompanyName());
			
			// Add user name property
			createRequestPropertyInfo(request, "username", user.getUsername());
			
			// Add password property
			createRequestPropertyInfo(request, "password", md5Password);
			
			// Add IMEI property
			createRequestPropertyInfo(request, "IMEI", user.getDeviceIMEI());
			
			// Add device provider property
			createRequestPropertyInfo(request, "deviceProvider", user.getDeviceProvider().getName());
			
			// Get the result of the web service request
			SoapObject response = getRequestResponse(request, methodName);
			
			String processUserDeviceResponse = response.getProperty("ProcessUserDeviceResult").toString();
			
			Element documentElement = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(processUserDeviceResponse.getBytes())).getDocumentElement();
			
			loginResult = MFTParser.processWebServiceResult(documentElement);
			
			user.setRoleList(MFTParser.processUserRoles(documentElement));
			user.setRegisteredDevicesNumber(MFTParser.processUserRegisteredDevicesNumber(documentElement));
			user.setDeviceLicensesNumber(MFTParser.processUserLicenseNumber(documentElement));
			
		} catch (Exception e) {
			System.out.println("Error in MFTWebService.login - trying to call ProcessUserDevice service");
			
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			
			e.printStackTrace();
		}
		
		return loginResult;
	}

	/***
	 * Returns response from the called specified method name web service using the specified request
	 * @param request
	 * @param methodName
	 * @return
	 * @throws IOException
	 * @throws XmlPullParserException
	 */
	protected SoapObject getRequestResponse(SoapObject request, String methodName)
			throws IOException, XmlPullParserException {
		
		// Create SOAP envelope
 		SoapSerializationEnvelope envelope = createSOAPEnvelope(request);
		
		// Create transport object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		
		String soapAction = NAMESPACE+"/"+methodName;
		
		// Invoke the web service and obtain the result
		androidHttpTransport.call(soapAction, envelope);
		SoapObject response = (SoapObject) envelope.bodyIn;
		
		return response;
	}
	
	/***
	 * Returns response from the called specified method name web service using the specified request and sending user auth info in the header
	 * @param request
	 * @param methodName
	 * @param user
	 * @return
	 * @throws IOException
	 * @throws XmlPullParserException
	 */
	protected SoapObject getRequestResponse(SoapObject request, String methodName, User user)
			throws IOException, XmlPullParserException {
		
		// Create SOAP envelope
 		SoapSerializationEnvelope envelope = createSOAPEnvelope(request);
 		//set authentication header
 		envelope.headerOut = new org.kxml2.kdom.Element[1];
 		envelope.headerOut[0] = buildAuthHeader(user);
		
		// Create transport object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		
		String soapAction = NAMESPACE+"/"+methodName;
		
		// Invoke the web service and obtain the result
		androidHttpTransport.call(soapAction, envelope);
		SoapObject response = (SoapObject) envelope.bodyIn;
		
		return response;
	}
	
	/***
	 * Register device for the specified user using the specified device information
	 * @param user
	 * @param device
	 * @return
	 */
	public WebServiceResult registerDevice(User user) {
		
		WebServiceResult registerDeviceResult = WebServiceResult.UNKNOWN_ERROR;
		
		try {
			
			String methodName = "AddDevice";
			
			SoapObject request = new SoapObject(NAMESPACE, methodName);
			
			XmlSerializer serializer = Xml.newSerializer();
			StringWriter requestOutputWriter = createXMLRequest(serializer, methodName.toUpperCase());
			
			// Writes the device information in the XML
			setDeviceXMLRequest(serializer, user);
			
			// Writes the user information in the XML
			setUserXMLRequest(serializer, user);
			
			finishXMLRequest(serializer, methodName.toUpperCase());
			
			// Add XML parameter to the request
			createRequestPropertyInfo(request, "xmlReq", requestOutputWriter.toString());
			
			// Get the result of the web service request
			SoapObject response = getRequestResponse(request, methodName, user);
			
			String AddDeviceResponse = response.getProperty(0).toString();
			
			Element documentElement = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(AddDeviceResponse.getBytes())).getDocumentElement();
			
			registerDeviceResult = MFTParser.processWebServiceResult(documentElement);
			
		} catch (Exception e) {
			System.out.println("Error in MFTWebService.registerDevice - trying to call AddDevice service");
			
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			
			e.printStackTrace();
		}
		
		return registerDeviceResult;
	}
	
	/***
	 * unregister device for the specified user using the specified device information
	 * @param user
	 * @param device
	 * @return
	 */
	public WebServiceResult unregisterDevice(User user) {
		
		WebServiceResult registerDeviceResult = WebServiceResult.UNKNOWN_ERROR;
		
		try {
			
			String methodName = "UnregisterDevice";
			
			SoapObject request = new SoapObject(NAMESPACE, methodName);
			
			XmlSerializer serializer = Xml.newSerializer();
			StringWriter requestOutputWriter = createXMLRequest(serializer, methodName.toUpperCase());
			
			// Writes the device information in the XML
			setDeviceXMLRequest(serializer, user);
			
			// Writes the user information in the XML
			setUserXMLRequest(serializer, user);
			
			finishXMLRequest(serializer, methodName.toUpperCase());
			
			// Add XML parameter to the request
			createRequestPropertyInfo(request, "xmlReq", requestOutputWriter.toString());
			
			// Get the result of the web service request
			SoapObject response = getRequestResponse(request, methodName, user);
			
			String unregisterDeviceResponse = response.getProperty(0).toString();
			
			Element documentElement = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(unregisterDeviceResponse.getBytes())).getDocumentElement();
			
			registerDeviceResult = MFTParser.processWebServiceResult(documentElement);
			
			//TODO: TREAT RETURN AND  IF SUCCESSFUL RESET LOGGED USER
			
		} catch (Exception e) {
			System.out.println("Error in MFTWebService.unregisterDevice - trying to call UnregisterDevice service");
			
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			
			e.printStackTrace();
		}
		
		return registerDeviceResult;
	}
	
	
	/***
	 * update password for the user that has a temporary password
	 * @param user
	 * @return
	 */
	public WebServiceResult updateNewPassword(User user, String newPassword) {
		
		WebServiceResult updateNewPasswordResult = WebServiceResult.UNKNOWN_ERROR;
		
		try {
			
			String methodName = "AccountUpdateUserPassword";
			String md5Password = getMD5Password(user.getPassword());
			
			String newMd5Password = getMD5Password(newPassword);
			
			SoapObject request = new SoapObject(NAMESPACE, methodName);
			
			// Add company name property
			createRequestPropertyInfo(request, "company", user.getCompanyName());

			// Add user name property
			createRequestPropertyInfo(request, "username", user.getUsername());

			// Add password property
			createRequestPropertyInfo(request, "password", md5Password);
			
			// Add new password property
			createRequestPropertyInfo(request, "newpassword", newMd5Password);

			// Get the result of the web service request
			SoapObject response = getRequestResponse(request, methodName);
			
			String updateNewPasswordResponse = response.getProperty(0).toString();
			
			Element documentElement = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(updateNewPasswordResponse.getBytes())).getDocumentElement();
			
			updateNewPasswordResult = MFTParser.processWebServiceResult(documentElement);
			
			//TODO: TREAT RETURN AND  IF SUCCESSFUL RESET LOGGED USER
			
		} catch (Exception e) {
			System.out.println("Error in MFTWebService.updateNewPassword - trying to call UpdateNewPassword service");
			
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			
			e.printStackTrace();
		}
		
		return updateNewPasswordResult;
	}
	
	
	/*** <pre>
	 * Add device XML request to the specified XmlSerializer using the specified device information 
	 * "<"DEVICE device_gps_id="imei" 
	 * 		serial="imei" 
	 * 		name="name" 
	 * 		driver_name="name" 
	 * 		device_provider="Android" 
	 * 		msisdn="line number"
	 * 		driver_cell="line number"
	 * 		driver_email="email@email.com"
	 * 	"/>"
	 * </pre>
	 * @param serializer
	 * @param device
	 */
	protected void setDeviceXMLRequest(XmlSerializer serializer, User user){

		try {
			
			serializer.startTag("", "DEVICE");
			
			if (user.getDeviceIMEI() != null){
				serializer.attribute("", "device_gps_id", user.getDeviceIMEI());
				serializer.attribute("", "serial", user.getDeviceIMEI());
			} else {
				serializer.attribute("", "device_gps_id", "");
				serializer.attribute("", "serial", "");
			} 
			
			if (user.getDeviceProvider() != null 
					&& user.getDeviceProvider().getName() != null){
				serializer.attribute("", "device_provider", user.getDeviceProvider().getName());
			} else {
				serializer.attribute("", "device_provider", "");
			} 
			
			if (user.getDeviceName() != null){
				serializer.attribute("", "name", user.getDeviceName());
				serializer.attribute("", "driver_name", user.getDeviceName());
			} else {
				serializer.attribute("", "name", "");
				serializer.attribute("", "driver_name", "");
			} 
			
			if (user.getDevicePhoneNumber() != null){
				serializer.attribute("", "msisdn", user.getDevicePhoneNumber());
				serializer.attribute("", "driver_cell", user.getDevicePhoneNumber());
			} else {
				serializer.attribute("", "msisdn", "");
				serializer.attribute("", "driver_cell", "");
			} 
			
			if (user.getDeviceDriverEmail() != null){
				serializer.attribute("", "driver_email", user.getDeviceDriverEmail());
			} else {
				serializer.attribute("", "driver_email", "");
			} 
			
			serializer.endTag("", "DEVICE");
		
		} catch (Exception e) {
			System.out.println("Error in MFTWebService.setDeviceXMLRequest - trying to create XML corresponding to a device");
			
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			
			e.printStackTrace();
		}
	}
	
	/***
	 * Register the specified user using the web service
	 * @param user
	 * @return
	 * @throws IOException
	 * @throws XmlPullParserException
	 * @throws ParserConfigurationException
	 */
	public WebServiceResult registerUser(User user) throws IOException,	XmlPullParserException, ParserConfigurationException {

		WebServiceResult registryResult =  WebServiceResult.UNKNOWN_ERROR;
		
		try {
			/*
			<REGISTRY name="">
            	<NEWCOMPANY company="">
            		<ROLES>
            			<ROLE name=""/>     
        			</ROLES>
              		<USERS>
                		<USER username="" pwd="" fullname="" email="" handy="" admin="">
                		<ROLES>
            				<ROLE name=""/>     
        				</ROLES>
                		</USER>
              		<USERS>
            	</NEWCOMPANY>
          	</REGISTRY>*/
			
			
			// Set up request
			String methodName = "Account_Registry";
			
			SoapObject request = new SoapObject(NAMESPACE, methodName);
			
			XmlSerializer serializer = Xml.newSerializer();
			
			StringWriter requestOutputWriter = createXMLRequest(serializer, "REGISTRY");
			
			serializer.startTag("", "NEWCOMPANY");
			serializer.attribute("", "company", user.getCompanyName());
			
			ArrayList<User> usersList = new ArrayList<User>();
			usersList.add(user);
			
			setUsersListXMLRequest(serializer, usersList);
			
			serializer.endTag("", "NEWCOMPANY");
			finishXMLRequest(serializer, "REGISTRY");
			
			createRequestPropertyInfo(request, "xmlRequest", requestOutputWriter.toString());

			// Get the result of the web service request
			SoapObject response = getRequestResponse(request, methodName);
			
			String AddDeviceResponse = response.getProperty(0).toString();
			
			Element documentElement = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(AddDeviceResponse.getBytes())).getDocumentElement();
			
			registryResult = MFTParser.processWebServiceResult(documentElement);
			

		} catch (Exception e) {
			System.out.println("Error in WebService.registerUser - trying to call Account_Registry service");

			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}

			e.printStackTrace();
		}
		
		return registryResult;
	}
	
	/***
	 * Finishes the XML request using the specified XmlSerializer and the the root tag name
	 * @param serializer
	 * @param rootTagName
	 * @throws IOException
	 */
	protected void finishXMLRequest(XmlSerializer serializer, String rootTagName)
			throws IOException {
		serializer.endTag("", rootTagName);
		serializer.endDocument();
	}
	
	/***
	 * Returns the writer containing the XML request using the specified XmlSerializer and the the root tag name
	 * @param serializer
	 * @param rootTagName
	 * @return
	 * @throws IOException
	 */
	protected StringWriter createXMLRequest(XmlSerializer serializer, String rootTagName)
			throws IOException {
		
		StringWriter writer = new StringWriter();
		serializer.setOutput(writer);
		serializer.startDocument(null, null);
		serializer.startTag("", rootTagName);
		return writer;
	}
	
	/*** <pre>
	 * Add a XML representing a list of user to the specified XmlSerializer using the specified Users information 
	 * "<"USERS>
	 * "<"USER username=userName' 
	 * 		pwd='password' 
	 * 		fullname='fullName' 
	 * 		email='email@email.com' 
	 * 		handy='phone' 
	 * 		admin='YEP'/">"
	 * "<"USER username=userName' 
	 * 		pwd='password' 
	 * 		fullname='fullName' 
	 * 		email='email@email.com' 
	 * 		handy='phone' 
	 * 		admin='YEP'/">"
	 * 		.
	 * 		.
	 * 		.
	 * "<"USERS\">"
	 * </pre>
	 * @param serializer
	 * @param usersList
	 */
	protected void setUsersListXMLRequest(XmlSerializer serializer, ArrayList<User> usersList){
		
		try {
			serializer.startTag("", "USERS");
			
			for(Iterator<User> usersListIterator = usersList.iterator();usersListIterator.hasNext();){
				User user = usersListIterator.next();
				setUserXMLRequest(serializer, user);
								
			}
			serializer.endTag("", "USERS");
			
		} catch (Exception e) {
			System.out.println("Error in MFTWebService.setUserXMLRequest - trying to create XML corresponding to a user");
			
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			
			e.printStackTrace();
			
		}
	}
	
	/*** <pre>
	 * Add user XML request to the specified XmlSerializer using the specified User information 
	 * "<"USER username="userName" 
	 * 		pwd="password" 
	 * 		fullname="fullName" 
	 * 		email="email@email.com" 
	 * 		handy="phone" 
	 * 		admin="YEP" "/>"
	 * </pre>
	 * @param serializer
	 * @param user
	 */
	protected void setUserXMLRequest(XmlSerializer serializer, User user){
		
		try {
			serializer.startTag("", "USER");
			
			if (user.getCompanyName() != null){
				serializer.attribute("", "company", user.getCompanyName());
			} else {
				serializer.attribute("", "company", "");
			}
			
			if (user.getUsername() != null){
				serializer.attribute("", "username", user.getUsername());
			} else {
				serializer.attribute("", "username", "");
			}
			
			if (user.getPassword() != null){
				serializer.attribute("", "pwd", getMD5Password(user.getPassword()));
			} else {
				serializer.attribute("", "pwd", "");
			}
			
			if (user.getFullName() != null){
				serializer.attribute("", "fullname", user.getFullName());
			} else {
				serializer.attribute("", "fullname", "");
			}
			
			if (user.getEmail() != null){
				serializer.attribute("", "email", user.getEmail());
			} else {
				serializer.attribute("", "email", "");
			}
			
			if (user.getPhone() != null){
				serializer.attribute("", "handy", user.getPhone());
			} else {
				serializer.attribute("", "handy", "");
			}
			
			serializer.attribute("", "admin", "YEP"); //TODO: verify if is needed to modify this method to make this attribute editable
			
			// Add all Roles for User
			setRolesForFreeUser(serializer);
			
			serializer.endTag("", "USER");
			
			
		} catch (Exception e) {
			System.out.println("Error in MFTWebService.setUserXMLRequest - trying to create XML corresponding to a user");
			
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			
			e.printStackTrace();
			
		}
	}

	/***
	 * Add Roles information for each User 
	 * @param serializer
	 */
	
	private void setRolesForFreeUser(XmlSerializer serializer) throws IOException {
		//TODO: We are adding here all roles that the free user must have
		serializer.startTag("", "ROLES");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.ADMIN.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.GEOFENCE_READ.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.GEOFENCE_WRITE.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.MESSAGES_READ.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.MESSAGES_WRITE.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.POI_READ.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.POI_WRITE.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.REPORTS_READ.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.REPORTS_WRITE.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.RULES_READ.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.RULES_WRITE.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.TRACK_READ.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.TRACK_WRITE.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.WORKORDER_READ.getText());
		serializer.endTag("", "ROLE");
		
		serializer.startTag("", "ROLE");							
		serializer.attribute("", "name", Role.WORKORDER_WRITE.getText());
		serializer.endTag("", "ROLE");
			
		serializer.endTag("", "ROLES");
	}
	
	
	/***
	 * Create request property info (method parameter) to the specified soap request, with the specified name and value
	 * @param soapRequest
	 * @param propertyName
	 * @param propertyValue
	 */
	protected void createRequestPropertyInfo(SoapObject soapRequest, String propertyName, String propertyValue) {
		
		try {
			PropertyInfo propertyInfo = new PropertyInfo();
			propertyInfo.setName(propertyName);
			propertyInfo.setValue(propertyValue);
			soapRequest.addProperty(propertyInfo);
		} catch (Exception e) {
			System.out.println("Error in WebService.createRequestPropertyInfo - trying to create property info for a soapRequest");
			if (e.getMessage() != null){
				System.out.println(e.getMessage());
			}
			e.printStackTrace();
		}
	}

	/***
	 * Create SOAP envelope with the specified request
	 * @param Request
	 * @return SOAP envelope
	 */
	protected SoapSerializationEnvelope createSOAPEnvelope(SoapObject Request) {
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(Request);
		return envelope;
	}
	
	/***
	 * Serialize specified password using MD5 hash algorithm 
	 * @param password
	 * @return serialized password
	 */
	protected String getMD5Password(String password) {
	    String result = "";
		try {
	        // Create MD5 Hash
	      
	        
	        MessageDigest md = MessageDigest.getInstance("MD5");
	        md.update(password.getBytes());
	 
	        byte byteData[] = md.digest();
	 
	        //convert the byte to hex format method 1
	        StringBuffer sb = new StringBuffer();
	        for (int i = 0; i < byteData.length; i++) {
	         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
	        }
	 
	        System.out.println("Digest(in hex format):: " + sb.toString());
	 
	        //convert the byte to hex format method 2
	        StringBuffer hexString = new StringBuffer();
	    	for (int i=0;i<byteData.length;i++) {
	    		String hex=Integer.toHexString(0xff & byteData[i]);
	   	     	if(hex.length()==1) hexString.append('0');
	   	     	hexString.append(hex);
	    	}
	    	
	        result = hexString.toString();
	        
	    } catch (NoSuchAlgorithmException e) {
	    	System.out.println("Error in WebService.getMD5Password - getting serailized password");
	    	if (e.getMessage() != null){
	    		System.out.println(e.getMessage());
	    	}
	        e.printStackTrace();
	    }
	    return result;
	}
			
	private org.kxml2.kdom.Element buildAuthHeader(User user) {
		org.kxml2.kdom.Element h = new org.kxml2.kdom.Element().createElement(NAMESPACE, "MFTSoapHeader");
		org.kxml2.kdom.Element company = new org.kxml2.kdom.Element().createElement(NAMESPACE, "COMPANY");
		company.addChild(org.kxml2.kdom.Node.TEXT, user.getCompanyName());
	    h.addChild(org.kxml2.kdom.Node.ELEMENT, company);
		org.kxml2.kdom.Element username = new org.kxml2.kdom.Element().createElement(NAMESPACE, "NICKNAME");
	    username.addChild(org.kxml2.kdom.Node.TEXT, user.getUsername());
	    h.addChild(org.kxml2.kdom.Node.ELEMENT, username);
	    org.kxml2.kdom.Element pass = new org.kxml2.kdom.Element().createElement(NAMESPACE, "PASSWORD");
	    pass.addChild(org.kxml2.kdom.Node.TEXT, user.getPassword());
	    h.addChild(org.kxml2.kdom.Node.ELEMENT, pass);

	    return h;
	}
	
	/***
	 * Returns the list of buddies associated with the specified user.
	 * @param user
	 * @param device
	 * @return
	 */
	public ArrayList<Buddy> listBuddies(User user) throws IOException,
			XmlPullParserException, ParserConfigurationException {

		ArrayList<Buddy> result = new ArrayList<Buddy>();

		try {
			// Set up request
			String methodName = "BuddiesLoadListOfBuddiesAsXml";

			SoapObject request = new SoapObject(NAMESPACE, methodName);

			// Get the result of the web service request
			SoapObject response = getRequestResponse(request, methodName, user);

			/* String processUserDeviceResponse = */
			String xml = response.getProperty(
					"BuddiesLoadListOfBuddiesAsXmlResult").toString();
			result = MFTParser.parseBuddies(xml);
		} catch (Exception e) {
			System.out.println("Error in WebService BuddiesLoadListOfBuddiesAsXml");
	    	if (e.getMessage() != null){
	    		System.out.println(e.getMessage());
	    	}
	        e.printStackTrace();
		}
		
		return result;
	}
}
